package processer

import (
	"github.com/siddontang/go-mysql/mysql"
	"github.com/siddontang/go-mysql/replication"
	"hermes/manager"
	"hermes/mysqldb"
)

func TableEventHandle(event *replication.TableMapEvent,position mysql.Position){

	tableName := string(event.Schema) + "." + string(event.Table)
	if TableFilterMessageByName(tableName){
		return
	}

	tableMetaDatas, ok := manager.SchemaMetaDataCache[tableName]
	var needGetSchemaInfo bool
	var needInitSchemaInfoMap bool
	if ok {
		needInitSchemaInfoMap = false
		_, ok := manager.SchemaMetaDataCache[tableName][event.TableID]
		if !ok {
			needGetSchemaInfo = true
		}
	}else {
		needGetSchemaInfo = true
		needInitSchemaInfoMap = true
	}
	if needGetSchemaInfo {
		tableInfos := mysqldb.GetTableNames(tableName)
		tableMetaData:= manager.TableMetaData{
			Table:tableName,
			TableID:event.TableID,
			Position:position,
			ColumnCount:event.ColumnCount,
			ColumnNames:tableInfos[0],
			ColumnTypes:event.ColumnType,
			ColumnTypeNames:tableInfos[1],
		}
		if needInitSchemaInfoMap {
			tableMetaDatas = map[uint64]manager.TableMetaData{event.TableID:tableMetaData}
		}else{
			tableMetaDatas[event.TableID] = tableMetaData
		}
		manager.SchemaMetaDataCache[tableName] = tableMetaDatas
		//TODO need insert into tsdb

	}
	//event.Dump(os.Stdout)
}